<template>
  <div class="out-box">
    <span class="top-title">{{ doctorData.isEdit | editOrAdd }}师傅信息：</span>
    <div class="info-picture-box">
      <div class="info-out-box">
        <div class="info-in-box" v-show="doctorData.isEdit">
          <span class="title" style="width: 10%;">编号：</span>
          <el-input v-model="doctorData.ID" placeholder="请输入内容" class="input-box" :disabled="true"></el-input>
        </div>
        <div class="info-in-box">
          <span class="title" style="width: 10%;">姓名：</span>
          <el-input v-model="doctorData.name" placeholder="请输入姓名" class="input-box"></el-input>
        </div>
        <div class="info-in-box" >
          <span class="title" style="width: 10%;">性别：</span>
          <el-select v-model="doctorData.gender" placeholder="请选择">
            <el-option
              v-for="item in genderSelectData"
              :key="item.genderID"
              :label="item.gender"
              :value="item.genderID">
            </el-option>
          </el-select>
        </div>
        <div class="info-in-box">
          <span class="title" style="width: 10%;">店铺：</span>
          <el-select v-model="doctorData.massageId" placeholder="请选择">
            <el-option
              v-for="item in massageList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="info-in-box">
          <span class="title" style="width: 10%;">简介：</span>
          <el-input
            type="textarea"
            placeholder="请输入师傅简介"
            v-model="doctorData.specialty"
            class="brief"
            maxlength="1000"
            :autosize="{ minRows: 2, maxRows: 6}"
            show-word-limit>
          </el-input>
        </div>
      </div>
<!--      师傅照片-->
      <span class="picture-title">上传师傅图片</span>
      <div class="picture-box" style="display: flex;">
        <img :src="doctorData.picture" class="picture" style="width: 150px;height: 150px;" v-show="doctorData.isEdit">
        <img src="../../.././assets/change.png" class="change-icon" style="width: 150px;height: 150px;" v-show="doctorData.isEdit">
        <el-upload
          action="https://massage.osako.top/massage/picture/upload"
          list-type="picture-card"
          :file-list="fileList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-change="handlePhoto"
          :class="{hide:hideUpload}"
          v-loading.fullscreen.lock="fullscreenLoading">
          <i class="el-icon-plus"></i>
        </el-upload>
      </div>
    </div>
    <el-button class="insure-button" type="primary" style="margin-top: 15px;"
               @click="uploadPicture" v-loading.fullscreen.lock="loading">确定</el-button>
  </div>

</template>

<script>
  import {addDoctor, updateDoctor} from "@/api/doctor";
  import {getOutpatientListById} from "@/api/outpatient";
  import {tips} from "@/common/js/optionTips";
  import {getMassageInfo} from "@/api/massage";
  import {getToken} from "@/utils/auth";
  import axios from "axios";

  export default {
    name: "doctorOption",
    props: {
      doctorData: {}
      },
    data() {
      return {
        loading: false,
        imgUrl: '',
        imgFile:{},
        //关于图片上传的
        hideUpload: false,
        fileList: [],
        dialogVisible: false,
        fullscreenLoading: false, // 进行整个屏幕的加载的
        status: '',// 用于记录当前状态是编辑还是添加
        // 上面的下拉框的店铺的数据
        jobTitleData: [{
          id: 1,
          jobTitle: '师傅'
        }],
        genderSelectData: [{
          genderID: 1,
          gender: '男'
        }, {
          genderID: 2,
          gender: '女'
        }],
        // 记录所有店铺的数据
        massageList: [],
        // 所属专科的数据
        departmentSelectData: [],
        // 所属门诊的数据
        outpatientSelectData: [],
      }
    },
    methods: {
      // 当上传了一张照片上去
      handlePhoto: function (file, fileList) {
        this.imgFile = file;
        this.hideUpload = fileList.length >= 1;
      },
      // 删除上传的照片
      handleRemove(file, fileList) {
        if (fileList.length === 0) {
          this.fileList = []
        } else {
          let dl = this.fileList.indexOf(file);
          this.fileList.splice(dl, 1)
        }
        this.hideUpload = fileList.length >= 1
      },
      handlePictureCardPreview(file) {
        this.imgUrl = file.url;
        this.dialogVisible = true;
      },
      //上传图片
      uploadPicture: function() {
         //如果是编辑师傅信息且没有上传图片，就不调用上传图片,不然会报错
         if(this.doctorData.isEdit && !this.hideUpload){
          this.updateDoctor()
          return;
        }
         if(this.doctorData.name === '' || this.doctorData.massageId=== '' || this.doctorData.specialty === '' || this.doctorData.gender === ''){
           tips('error','请完善师傅信息')
           return;
         }
        //未上传图片
        if(!this.hideUpload){
          tips('error','请上传师傅图片')
          return;
        }
        //进行全屏幕加载
        this.fullscreenLoading = true;
        const url = 'https://massage.osako.top/massage/picture/upload';
        const config = {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': getToken()
          }
        };
        const param = new FormData();
        // 将图片加入formdata
        param.append('file', this.imgFile.raw);
        axios.post(url, param, config).then(res => {
          if (res.data.code === 200) {
            //图片url
            //console.log(res.data.data)
            this.doctorData.picture = res.data.data
            this.imgUrl = res.data.data;
            // console.log('this.doctorData.picture'+this.doctorData.picture)
            // console.log('this.imgUrl'+this.imgUrl)
            this.validateData()
          }
        }).catch(() => {
          this.fullscreenLoading = false;
          this.$notify.error({
            title: '错误',
            message: '上传图片失败'
          });
        });
      },
      // 对表单进行遍历
      validateData: function() {
        let isValidate = true;
        for(let item in this.doctorData) {
          console.log(item+' '+this.doctorData[item])
          if (this.doctorData[item] === '' || this.doctorData[item] === undefined
            || this.doctorData[item] === null) {
            isValidate = false;
            this.$message.error('请完善基本信息');
            //console.log(this.imgUrl)
            //console.log(this.doctorData.picture)
            break;
          } // end if
        } // end for
        if (isValidate) {
          if (this.doctorData.isEdit) {
            console.log('更新')
            this.updateDoctor()
          } else {
            console.log('添加')
            this.addDoctor()
          } // end if
        } // end if
      },
      // 向数据库添加师傅数据
      addDoctor: function () {
        this.loading = true;
        addDoctor({
          gender: this.doctorData.gender,
          jobTitle: this.doctorData.jobTitle,
          name: this.doctorData.name,
          outpatientId: this.doctorData.outpatientId,
          specialId: this.doctorData.specialId,
          specialty: this.doctorData.specialty,
          massageId: this.doctorData.massageId,
          img: this.doctorData.picture
        }).then(res => {
          if (res.code === 200) {
            this.fullscreenLoading = false;
            this.loading = false;
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success'
            });
            this.$router.push({path: '/doctorDetail'})
          }
        }).catch(() => {
          this.loading = false;
          tips('error', '添加失败')
        })
      },
      // 更新师傅信息
      updateDoctor: function () {
        if(this.doctorData.name === '' || this.doctorData.massageId=== '' || this.doctorData.specialty === '' || this.doctorData.gender === ''){
          tips('error','请完善师傅信息')
          return;
        }
        this.loading = true;
        updateDoctor(this.doctorData.ID, {
          gender: this.doctorData.gender,
          jobTitle: this.doctorData.jobTitle,
          name: this.doctorData.name,
          outpatientId: this.doctorData.outpatientId,
          specialId: this.doctorData.specialId,
          specialty: this.doctorData.specialty,
          massageId: this.doctorData.massageId,
          img:  this.doctorData.picture
        }).then(res => {
          if (res.code === 200) {
            this.fullscreenLoading = false;
            this.loading = false;
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success'
            });
            this.$router.push({path: '/doctorDetail'})
          }
        }).catch(() => {
          this.loading = false;
          tips('error', '修改失败')
        })
      },
      // 获取所有店铺
      getAllMassage: function (){
        getMassageInfo(1,50).then(res=>{
          //console.log(res);
          //请求成功
          if (res.code === 200 && res.data.list.length > 0){
            this.massageList = res.data.list;
            this.doctorData.massageName = this.massageList[0].name;
            this.doctorData.massageId = this.massageList[0].id;
          }
        }).catch(()=>{
          tips('error','获取店铺信息失败，请检查网络');
        })
      },
// 获取专科的门诊信息
    },
    created() {
      this.doctorData.jobTitle = '师傅'
      this.getAllMassage();
      this.massageList = JSON.parse(sessionStorage.getItem('departmentList'));
      this.departmentSelectData = JSON.parse(sessionStorage.getItem('departmentList'));
      this.outpatientSelectData = JSON.parse(sessionStorage.getItem('outpatientList'));
    },
  }
</script>

<style lang="scss">
  @import "../../.././common/scss/common.scss";
  .out-box{
    @include width-margin(90%, 100%);
    @include flex-direction(column);
    margin-top: 20px;
    // 上面的标题和按钮
    .top-title{
      @include font-style(18px, $major-blue-color);
      margin-right: 40px;
      display: flex;
      align-items: center;
    }
    .brief{
     width: 90%;
     height:100%;
     margin:0 auto;
    }
    //上传图片的标题
    .picture-title{
      height:20px;
      width:120px;
    }
    // 中间的信息
    .info-picture-box{
      @include width-margin(100%, 100%);
      @include flex-direction(row);
      margin-top: 20px;
      .info-out-box{
        width: 50%;
        height: 100%;
      }
      .brief-box{
        @include width-margin(50%,auto);
        @include flex-direction(column);
        text-align: center;
        margin-left: 5%;
        .title{
          width: 100%;
          height: 40px;
          line-height: 40px;
          @include font-style(16px, #000000);
        }
        .brief{
          @include width-margin(80%, auto);
          margin-left: 5%;
        }
      }
    }
  }

</style>
